package com.to8to.kitt.esb.http;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.to8to.kitt.utils.LogPatterns;
import com.to8to.kitt.utils.LogUtils;

public class HttpSCFutureListener implements ChannelFutureListener{

	public static Logger logger = LoggerFactory.getLogger(HttpSCFutureListener.class);  
	
	private HttpBusMessageState status;
	
	public HttpSCFutureListener(HttpBusMessageState status)
	{
		this.status = status;
	}
	
	@Override
	public void operationComplete(ChannelFuture future)
			throws Exception {
		
		LogUtils.openTag(status.getTag());
		
		status.recordFinishSendClientTime();
		
		String head = status.inMsg.getHead().name;
		
		if(future.isSuccess())
		{	
			if(status.finishSendClientTime - status.recvFromClientTime > 100)
				logger.warn(LogPatterns.SEND_TO_CLIENT + "\n<<<耗时分析(超时):{}>>>", future.channel().toString(), future.channel().remoteAddress().toString()
					, status.getOldseq(), status.getNewseq(), head, status.spendTimeString());
			else 
				logger.debug(LogPatterns.SEND_TO_CLIENT + "\n<<<耗时分析:{}>>>", future.channel().toString(), future.channel().remoteAddress().toString()
						, status.getOldseq(), status.getNewseq(), head, status.spendTimeString());
		}
		else 
		{
			boolean isOpen = future.channel().isOpen();
			boolean isActive = future.channel().isActive();
			boolean isRegistered = future.channel().isRegistered();
			boolean isWritable = future.channel().isWritable();
			
			logger.info(LogPatterns.SEND_TO_CLIENT_FAIL + "\n isOpen: " + isOpen + "  isActive: " + isActive + "  isRegistered: " + isRegistered+ "  isWritable: " + isWritable, future.channel().toString(), future.channel().remoteAddress().toString()
					, status.getOldseq(), status.getNewseq(), head);
		}
		
		LogUtils.removeTag();
		
		future.removeListener(this);
	}
}